/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * koneksi.java
 *
 * Created on 29 Jun 11, 12:54:10
 */

package koneksi;

import com.jtattoo.plaf.bernstein.BernsteinLookAndFeel;
import dudinzpos.mainView;
import java.awt.*;
import java.io.*;
import java.sql.*;
import java.util.Properties;//import yang ini untuk menyimpan data sementara
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import property.theme;

/**
 *
 * @author UserXP
 */
public class koneksi extends javax.swing.JFrame {

    private String PROP_FILE="config.ini";
    private Properties p2;

    private String jServer;
    private String jUser;
    private String jPassword;
    private String jDatabase;
    private String urlValue;
    private Connection ConnectionObj;
    public boolean blnIsConnected=false;
    public boolean blninitComponent=false;




    // inisialisasi setter & getter.. copazz mode on :)
    public void setServer(String value){
        jServer=value;
    }
    public void setUser(String value){
        jUser=value;
    }
    public void setPassword(String value){
        jPassword=value;
    }
    public void setDatabase(String value){
        jDatabase=value;
    }

    public String getServer(){
        return jServer;
    }
    public String getUser(){
        return jUser;
    }
    public String getPassword(){
        return jPassword;
    }
    public String getDatabase(){
        return jDatabase;
    }
    public Connection getConnection(){
    return ConnectionObj;
    }
    // method kendali utama kelas...
    //.. Andeng-andeng ono pilingan, ojo dipandeng mundak kelingan....(walang kekek..
    public boolean isConnected(){
        return blnIsConnected;
    }
    public boolean makeinitConnect(){
        try{
        p2 = loadProperties(PROP_FILE);//Mendapatkan nilai key
	jServer=p2.getProperty("SERVER");
	jUser=p2.getProperty("USER");
        jPassword=p2.getProperty("PASSWORD");
        jDatabase=p2.getProperty("DATABASE");
        blninitComponent=true;
        }catch(Exception e){
            JOptionPane.showMessageDialog(this, "initComponenet gagal!!");
        }

        return blninitComponent;
    }
    public boolean makeConnect(){
        try{
            Class.forName("com.mysql.jdbc.Driver");
            urlValue="jdbc:mysql://"+jServer+"/"+jDatabase+"?user="+jUser+
                    "&password="+jPassword;
            ConnectionObj=DriverManager.getConnection(urlValue);
            blnIsConnected=true;
        }catch(SQLException e){
            jTextArea1.setText("Kesalahan pada SQL \n mohon periksa " +
                    "kembali Setting Database");
        }catch(ClassNotFoundException e){
            jTextArea1.setText("Kelas tidak ditemukan...");
        }

        return blnIsConnected;
    }
     public void BuatKoneksiDB(){
        makeinitConnect();
        makeConnect();
    }
    public  Properties loadProperties(String sFile) {
      Properties p1 = new Properties();
      try {
	FileInputStream in = new FileInputStream(sFile);
	p1.load(in);
	in.close();
      } catch (IOException iOException) {
 	System.out.println(iOException);
      }

      return p1;
   }
    public static void saveProperties(Properties p, String sFile)
       throws IOException{

   FileOutputStream out = null;
   try {
	out = new FileOutputStream(sFile);
	p.store(out, "Ini baris komentar\nFile konfigurasi");

   } catch (FileNotFoundException ex) {
	JOptionPane.showMessageDialog(null, ex.getMessage());
   } finally {
        try {
	   out.close();
         } catch (IOException ex) {
	    JOptionPane.showMessageDialog(null, ex.getMessage());
         }
    }
   }
  public void loadConfig(){
        p2 = loadProperties(PROP_FILE);//Mendapatkan nilai key

	txtServer.setText(p2.getProperty("SERVER"));
	txtUser.setText(p2.getProperty("USER"));
        txtPassword.setText(p2.getProperty("PASSWORD"));
        txtDatabase.setText(p2.getProperty("DATABASE"));
  }
    /** Creates new form Koneksi */
    

    /** Creates new form koneksi */
    public koneksi() {
       /* theme.temaUtama();
        * 
        */
        initComponents();
        property.frameUtility.setDitengah(this);
        loadConfig();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtServer = new javax.swing.JTextField();
        txtUser = new javax.swing.JTextField();
        txtPassword = new javax.swing.JPasswordField();
        txtDatabase = new javax.swing.JTextField();
        btnConnect = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Koneksi Database");

        jLabel1.setText("Server");

        jLabel2.setText("Username");

        jLabel3.setText("Password");

        jLabel4.setText("Database");

        txtServer.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtServerKeyTyped(evt);
            }
        });

        txtUser.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtUserKeyTyped(evt);
            }
        });

        txtPassword.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtPasswordKeyTyped(evt);
            }
        });

        txtDatabase.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtDatabaseKeyTyped(evt);
            }
        });

        btnConnect.setText("Connect...");
        btnConnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConnectActionPerformed(evt);
            }
        });
        btnConnect.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                btnConnectKeyTyped(evt);
            }
        });

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jLabel5.setText("Status :");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4))
                        .addGap(25, 25, 25)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE)
                            .addComponent(txtUser, javax.swing.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE)
                            .addComponent(txtDatabase, javax.swing.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE)
                            .addComponent(txtServer, javax.swing.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE)
                            .addComponent(btnConnect)))
                    .addComponent(jLabel5))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtServer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtDatabase, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(btnConnect)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnPejet(){
         String user=txtUser.getText();
        String pwd=String.copyValueOf(txtPassword.getPassword(),0,
                txtPassword.getPassword().length);
        String host=txtServer.getText();
        String db=txtDatabase.getText();

        jServer=host;
        jUser=user;
        jPassword=pwd;
        jDatabase=db;

        String urlValue="";
        makeConnect();

        if(blnIsConnected==true){
            jTextArea1.setText("Database Terhubung\ndengan baik.\nHave Fun!!");
        }else{
            jTextArea1.setText("Koneksi gagal\n periksa engine MySQL!");
        }
        if (blnIsConnected){
            if(this.getTitle().equals("Koneksi Database Baru")){
                JOptionPane.showMessageDialog(this, "Koneksi Sukses !");
                this.dispose();
            }else{
         JOptionPane.showMessageDialog(this, "Koneksi Sukses !");
         mainView mv=new mainView();
         mv.setExtendedState(JFrame.MAXIMIZED_BOTH);
         mv.setVisible(true);
         this.dispose();
            }

        }else{
         JOptionPane.showMessageDialog(this, "Koneksi Gagal !");
        }

        //blok try-catch untuk menyimpan default koneksi database
        try{
            Properties p=new Properties();
            p.setProperty("SERVER",txtServer.getText());
            p.setProperty("USER",txtUser.getText());
            p.setProperty("PASSWORD", String.copyValueOf(txtPassword.getPassword(),0,
                txtPassword.getPassword().length));
            p.setProperty("DATABASE", txtDatabase.getText());
            saveProperties(p, PROP_FILE);
        }catch(IOException e){
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
    }
    private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConnectActionPerformed
        // TODO add your handling code here:
       btnPejet();
    }//GEN-LAST:event_btnConnectActionPerformed

    private void txtServerKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtServerKeyTyped
        // TODO add your handling code here:
        if(evt.getKeyChar()==evt.VK_ENTER)
            txtUser.requestFocus();
    }//GEN-LAST:event_txtServerKeyTyped

    private void txtUserKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtUserKeyTyped
        // TODO add your handling code here:
        if(evt.getKeyChar()==evt.VK_ENTER)
            txtPassword.requestFocus();
    }//GEN-LAST:event_txtUserKeyTyped

    private void txtPasswordKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPasswordKeyTyped
        // TODO add your handling code here:
        if(evt.getKeyChar()==evt.VK_ENTER)
            txtDatabase.requestFocus();
    }//GEN-LAST:event_txtPasswordKeyTyped

    private void txtDatabaseKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDatabaseKeyTyped
        // TODO add your handling code here:
        if(evt.getKeyChar()==evt.VK_ENTER)
            btnConnect.requestFocus();
    }//GEN-LAST:event_txtDatabaseKeyTyped

    private void btnConnectKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnConnectKeyTyped
        // TODO add your handling code here:
        if(evt.getKeyChar()==evt.VK_ENTER)
            btnPejet();
    }//GEN-LAST:event_btnConnectKeyTyped

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
               /*/ theme.temaUtama();
                *
                */
                new koneksi().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnConnect;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField txtDatabase;
    private javax.swing.JPasswordField txtPassword;
    private javax.swing.JTextField txtServer;
    private javax.swing.JTextField txtUser;
    // End of variables declaration//GEN-END:variables

}
